package com.hz.qs.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author yejy
 * @date 2020/10/29 21:02
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${spring.profiles.active}")
    private String profile;

    private static final String PROFILE  = "dev";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (PROFILE.equals(profile)) {
            return true;
        } else {
            Object userInfo = request.getSession().getAttribute("userInfo");
            //判断name是否存在，存在释放，不存在拦截，转发到登陆页面并且提示没有权限！
            if (userInfo == null) {
                request.setAttribute("loginMsg", "没有权限请先登陆");
                response.setStatus(401);
                return false;
            } else {
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //拦截中
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //拦截后
    }

}
